package com.aiju.cash.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Shop;
import com.aiju.cash.R;
import com.aiju.cash.core.api.BlotterApi;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.event.BlotterEvent;
import com.aiju.cash.ui.good.adapter.TeamsAndHeaderAdapter;
import com.aiju.cash.ui.main.adapter.BlotterAdater;
import com.aiju.cash.ui.main.entity.BlotterList;
import com.aiju.cash.ui.main.entity.Select;
import com.aiju.cash.ui.main.entity.SelectDate;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.support.recyclerView.DividerItemDecoration;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 流水选择条件界面
 *
 * @author 流冥
 */
public class BlotterSelectActivity extends BaseTitleActivity implements View.OnClickListener {


    private int currentNum = 1;
    private int pageSize = 10;
    private View empty;
    private RecyclerView recyclerviewTeams;
    private LinearLayoutManager mTeamsLayoutManager;
    private BlotterAdater mBlotterAdater;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private SwipeRefreshHelper mSwipeRefreshHelper;
    private RecyclerAdapterWithHF mAdapter;
    private BlotterApi mBlotterApi;
    private boolean isLoad;

    private boolean isRefresh;


    private TextView shop;
    private TextView employee;
    private TextView date;
    private TextView other;
    private TextView sum;
    private TextView gathering;
    private TextView refund;
    private TextView date_range;
    Context mContext = BlotterSelectActivity.this;
    private Select mSelect;
    private int SHOP_REQUESTCODE = 1;
    private int EMPLOYEE_REQUESTCODE = 2;
    private int DATE_REQUESTCODE = 3;
    private int OTHER_REQUESTCODE = 4;

    private String tempKsxz = "";
    private String tempJylx = "";

    //默认
    private String selectStoreId = "";
    private String selectOperatorId = "";

    private List<Shop> shopList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_blotter_select);
        initView();
    }


    private void initView() {
        setCenterTitle("流水");
        mAiJuTitleBarView.setRightTitle("恢复默认");
        empty = findViewById(R.id.iv_empty);
        recyclerviewTeams = (RecyclerView) findViewById(R.id.recyclerview_teams);
        shop = (TextView) findViewById(R.id.shop);
        date = (TextView) findViewById(R.id.date);
        other = (TextView) findViewById(R.id.other);
        employee = (TextView) findViewById(R.id.employy);
        sum = (TextView) findViewById(R.id.sum);
        gathering = (TextView) findViewById(R.id.gathering);
        refund = (TextView) findViewById(R.id.refund);
        date_range = (TextView) findViewById(R.id.date_range);
        shop.setOnClickListener(this);
        date.setOnClickListener(this);
        other.setOnClickListener(this);
        employee.setOnClickListener(this);
        mTeamsLayoutManager = new LinearLayoutManager(this);
        recyclerviewTeams.setLayoutManager(mTeamsLayoutManager);
        recyclerviewTeams.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sryt_swipe_listview);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.app_title_color));
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSwipeRefreshLayout);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onfresh() {
                L.d("onfresh");
                isRefresh = true;
                currentNum = 1;
                map.clear();
                getBlotterList();
            }
        });
        mSwipeRefreshHelper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshHelper.loadMoreComplete(true);
                    return;
                }
                L.d("loadMore");
                isLoad = true;
                ++currentNum;
                getBlotterList();
            }
        });
        mBlotterApi = new BlotterApi();
        requestShopList();
        initHeaderData();
        initHeader();
        getBlotterList();
        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(BlotterEvent event) {
                mAiJuTitleBarView.post(new Runnable() {
                    @Override
                    public void run() {
                        L.d("BlotterFragment：BlotterEvent");
                        mSwipeRefreshHelper.autoRefresh();
                    }
                });
            }
        }).tryToRegisterIfNot();

        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRefresh = true;
                currentNum = 1;
                map.clear();
                initHeaderData();
                initHeader();
                getBlotterList();
            }
        });
    }

    void requestShopList() {
        mBlotterApi.queryShopList(mUser, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson json = new DataJson(response);
                if ("操作成功".equals(json.getMsg())) {
                    if (json.getData() != null) {
                        shopList = new Gson().fromJson(json.getData().toString(), new TypeToken<List<Shop>>() {
                        }.getType());
                    }
                } else {
                    T.ToastShort("网络异常");
                }

            }
        });
    }

    private void getBlotterList() {
        mDialogHelper.showLoadingProgressDialog();
        L.d("当前页：" + String.valueOf(currentNum));
        String operatorId = "";
//        if (!mUser.isAdmin()) {
//            operatorId = mUser.getOperatorId();
//        }
        String date = "";
        if ("自定义".equals(mSelect.getDateDes())) {
            date = mSelect.getCommitStartTime() + "," + mSelect.getCommitEndTime();
        } else {
            date = mSelect.getDateTrans();
        }
        Log.i("detail", mSelect.toString());
        Log.i("detail", "currentPage:" + currentNum);
        mBlotterApi.queryDealStatistics(mUser, mSelect.getQueryStoreId(), mSelect.getOperatorId(), date, mSelect.getPayType(), mSelect.getTradeType(), currentNum + "", pageSize + "", new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson json = new DataJson(response);
                if (json.isSuccess()) {
                    List<BlotterList> list = new Gson().fromJson(json.getData().toString(), new TypeToken<List<BlotterList>>() {
                    }.getType());

                    try {
                        JSONObject jsonObject = new JSONObject(json.getExt());
                        mSelect.setSum(jsonObject.optString("totalMoney"));
                        mSelect.setGathering(jsonObject.optString("payTotalCount"));
                        mSelect.setRefund(jsonObject.optString("refundTotalCount"));
                        initHeader();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                    if ("null".equals(json.getData().toString())||list.size()==0) {//无数据处理
//                    if (list.size()==0) {//无数据处理
//                        blotterLists.clear();
//                        empty.setVisibility(View.VISIBLE);
//                        recyclerviewTeams.setVisibility(View.GONE);
//                        initHeader();
//                        completeView(list);
//                        return;
//                    }
                    setBlotterListView(list);

                } else {
//                    T.ToastShort(json.getMsg());
                    Log.i("AiJu", json.getMsg());
                    mSelect.setSum("0");
                    mSelect.setGathering("0");
                    mSelect.setRefund("0");
                    empty.setVisibility(View.VISIBLE);
                    recyclerviewTeams.setVisibility(View.GONE);
                    isRefresh = false;
                    mSwipeRefreshHelper.refreshComplete();
                }
            }
        });
    }

    List<BlotterList> blotterLists = new ArrayList<>();
    Map<String, BlotterList> map = new HashMap<>();

    /**
     * 处理数据
     */
    private void soreData() {
        Object[] key = map.keySet().toArray();
        Arrays.sort(key);
        for (int i = 0; i < key.length; i++) {
            blotterLists.add(map.get(key[i]));
        }
        Collections.reverse(blotterLists);
    }

    private void setBlotterListView(List<BlotterList> list) {
        for (BlotterList blotter : list) {
            BlotterList blotterList = map.get(blotter.getDate());
            if (blotterList != null) {
                blotterList.getList().addAll(blotter.getList());
            } else {
                map.put(blotter.getDate(), blotter);
            }
        }
        if (mAdapter == null) {
            soreData();
            mBlotterAdater = new BlotterAdater(this, blotterLists);
            mAdapter = new RecyclerAdapterWithHF(mBlotterAdater);
            recyclerviewTeams.setVisibility(View.VISIBLE);
            recyclerviewTeams.setAdapter(mAdapter);
            final StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(mBlotterAdater);
            recyclerviewTeams.addItemDecoration(headersDecor);
            mBlotterAdater.setOnItemClickListener(new TeamsAndHeaderAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Intent intent = new Intent(BlotterSelectActivity.this, BlotterInfoActvity.class);
                    intent.putExtra("id", mBlotterAdater.getTeamList().get(position).getId());
                    intent.putExtra("title", mBlotterAdater.getTeamList().get(position).getReceTypeDesc());
                    startActivity(intent);
                }
            });
        } else {
            blotterLists.clear();
            soreData();
            mBlotterAdater.setCategoryList(blotterLists);
        }
        completeView(list);
    }

    /**
     * 加载完成视图动作
     *
     * @param blotterLists
     */
    private void completeView(List<BlotterList> blotterLists) {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }

        if (getDataSize(blotterLists) < pageSize) {
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        } else {
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        // TODO: 2017/6/15 暂时 注释
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (mBlotterAdater != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = mBlotterAdater.getItemCount() == 0;
            if (emptyViewVisible) {
                //T.ToastShort("没有相关数据");
                empty.setVisibility(View.VISIBLE);
                recyclerviewTeams.setVisibility(View.GONE);
            } else {
                empty.setVisibility(View.GONE);
                recyclerviewTeams.setVisibility(View.VISIBLE);
            }
        }
    }

    private int getDataSize(List<BlotterList> blotterLists) {
        int size = 0;
        for (BlotterList blotterList : blotterLists) {
            size += blotterList.getList().size();
        }
        return size;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.shop:
                // TODO: 2017/6/15 跳转选择店铺界面
                Intent intent3 = new Intent(mContext, SelectShopActivity.class);
                intent3.putExtra("selectStoreId", selectStoreId);
                startActivityForResult(intent3, SHOP_REQUESTCODE);
                break;
            case R.id.employy:
                // TODO: 2017/6/15 跳转选择店员界面
                Intent intent2 = new Intent(mContext, SelectEmployeeActivity.class);
                intent2.putExtra("storeId", mSelect.getQueryStoreId());
                intent2.putExtra("selectOperatorId", selectOperatorId);
                startActivityForResult(intent2, EMPLOYEE_REQUESTCODE);
                break;
            case R.id.date:
                // TODO: 2017/6/15 跳转选择日期界面
                Intent intent = new Intent(mContext, SelectDateActivity.class);
                Bundle b = new Bundle();
                b.putSerializable("dd", mSelect);
                intent.putExtras(b);
                startActivityForResult(intent, DATE_REQUESTCODE);
                break;
            case R.id.other:
                // TODO: 2017/6/15 跳转选择其他界面
                Intent intent1 = new Intent(mContext, SelectOtherActivity.class);
                Bundle b1 = new Bundle();
//                b1.putSerializable("dd", mSelect);
                b1.putString("ksxz", tempKsxz);
                b1.putString("jylx", tempJylx);
                intent1.putExtras(b1);
                startActivityForResult(intent1, OTHER_REQUESTCODE);
                break;

        }
    }

    void initHeaderData() {
        Calendar lastDate = Calendar.getInstance();
        lastDate.roll(Calendar.DATE, -6);
        mSelect = new Select();
        mSelect.setShopName("全部门店");
        mSelect.setEmployName("全部店员");
        mSelect.setDateDes("近7日");
        mSelect.setDateTrans("nearly7");
        mSelect.setOther("其他");
        mSelect.setSum("0");
        mSelect.setGathering("0");
        mSelect.setRefund("0");
        mSelect.setStartDate(dateFormatYYYYmmdd(lastDate.getTime()));
        mSelect.setEndDate(dateFormatYYYYmmdd(new Date()));
        mSelect.setCommitStartTime(dateFormatYYYYmmdd1(lastDate.getTime()));
        mSelect.setCommitEndTime(dateFormatYYYYmmdd1(new Date()));
        mSelect.setFirstDate(lastDate.getTime());
        mSelect.setLastDate(new Date());
        mSelect.setPayType("支付宝,微信支付,现金,二维码台卡");
        mSelect.setTradeType("1,2");
        mSelect.setOperatorId("");
        mSelect.setQueryStoreId("");
        selectOperatorId = "";
        selectStoreId = "";
    }

    void initHeader() {
        shop.setText(mSelect.getShopName());
        employee.setText(mSelect.getEmployName());
        date.setText(mSelect.getDateDes());
        other.setText(mSelect.getOther());
        date_range.setText(replyDate(mSelect));
        sum.setText("￥" + mSelect.getSum());
        gathering.setText(mSelect.getGathering());
        refund.setText(mSelect.getRefund());
    }

    private String replyDate(Select select) {
        if (select.getStartDate().equals(select.getEndDate()))
            return select.getStartDate();
        else
            return select.getStartDate() + " - " + select.getEndDate();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == SHOP_REQUESTCODE && resultCode == RESULT_OK) {
                String storeId = data.getStringExtra("storeId");
                String shopName = data.getStringExtra("shopName");
                mSelect.setShopName(shopName);
                mSelect.setQueryStoreId(storeId);
                if (!selectStoreId.equals(storeId)) {//切换不同门店时，店员改为全部店员
                    mSelect.setOperatorId("");
                    mSelect.setEmployName("全部店员");
                    selectOperatorId = "";
                }

                selectStoreId = storeId;
            } else if (requestCode == EMPLOYEE_REQUESTCODE && resultCode == RESULT_OK) {
                String userName = data.getStringExtra("userName");
                String operatorId = data.getStringExtra("operatorId");
                String storeId = data.getStringExtra("storeId");
                mSelect.setEmployForStoreId(storeId);
                mSelect.setEmployName(userName);
                mSelect.setOperatorId(operatorId);
                selectOperatorId = operatorId;
                if (!mSelect.getQueryStoreId().equals(storeId)) {
                    setStoreName();
                }
            } else if (requestCode == DATE_REQUESTCODE && resultCode == RESULT_OK) {
                SelectDate date = (SelectDate) data.getSerializableExtra("date");
                mSelect.setStartDate(dateFormatYYYYmmdd(date.getStartDate()));
                mSelect.setEndDate(dateFormatYYYYmmdd(date.getEndDate()));
                mSelect.setCommitStartTime(dateFormatYYYYmmdd1(date.getStartDate()));
                mSelect.setCommitEndTime(dateFormatYYYYmmdd1(date.getEndDate()));
                mSelect.setDateDes(date.getName());
            } else if (requestCode == OTHER_REQUESTCODE && resultCode == RESULT_OK) {
//                mSelect = (Select) data.getSerializableExtra("result");
                tempKsxz = data.getStringExtra("ksxz");
                tempJylx = data.getStringExtra("jylx");
                mSelect.setPayType(data.getStringExtra("ksxz"));
                mSelect.setTradeType(data.getStringExtra("jylx"));
                mSelect.setOther(data.getStringExtra("other"));
            }
            initHeader();
            isRefresh = true;
            currentNum = 1;
            map.clear();
            getBlotterList();
            Log.i("detail", mSelect.toString());
        }

    }


    public static String dateFormatYYYYmmdd(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

    public static String dateFormatYYYYmmdd1(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


//    private String transMoney(String s) {
//        StringBuilder sb = new StringBuilder(s);
//        if (s.length() == 1) {
//            return "0.0" + s;
//        } else if (s.length() == 2) {
//            return "0." + s;
//        } else if (s.length() < 7) {
//            sb.insert(sb.length() - 2, ".");
//            return sb.toString();
//        } else {
//            String beforePoint = sb.toString().substring(0, sb.length() - 6);
//            String afterPoint = sb.toString().substring(sb.length() - 6, sb.length() - 4);
//            int i = Integer.parseInt(afterPoint);
//            int i1 = i % 10;
//            if (i1 >= 5) {
//                String s1 = (Integer.parseInt(afterPoint) + 1) + "";
//                return beforePoint + "." + s1 + "万";
//            } else {
//                return beforePoint + "." + afterPoint + "万";
//            }
//
//        }

//    }

    public void setStoreName() {
        for (int i = 0; i < shopList.size(); i++) {
            if (shopList.get(i).getStoreId().equals(mSelect.getEmployForStoreId())) {
                mSelect.setShopName(shopList.get(i).getShopName());
                break;
            }
        }
    }


}
